package thread;

import java.util.Scanner;

//wait 和 notify的使用
public class Demo16 {
    //同一对象调用多个wait的情况，需要多个notify唤醒或者notifyall来唤醒，但是存在随机调度和多个线程竞争同一个锁的情况，具体线程执行顺序其实并不可控
    public static void main(String[] args) {
        Object locker = new Object();


        Thread t1 = new Thread(() -> {
            try {
                System.out.println("t1开始");
                synchronized (locker){
                    locker.wait();
                }
                System.out.println("t1结束");
            }catch (InterruptedException e){
                throw new RuntimeException();
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                System.out.println("t2开始");
                synchronized (locker){
                    locker.wait();
                }
                System.out.println("t2结束");
            }catch (InterruptedException e){
                throw new RuntimeException();
            }
        });

        Thread t3 = new Thread(() -> {
            Scanner sc = new Scanner(System.in);
            System.out.println("输入任意值唤醒一个线程");
            sc.nextInt();//也是一种阻塞
            synchronized (locker){
                locker.notifyAll();//唤醒全部
            }
//            synchronized (locker) {
//                locker.notify();
//            }
//            System.out.println("唤醒另外一个");
//            sc.nextInt();
//            synchronized (locker) {
//                locker.notify();
//            }
        });


        t1.start();
        t2.start();
        t3.start();
    }


    public static void main1(String[] args) {
        Object locker = new Object();

        Thread t1 = new Thread(() -> {
            try {
                //Thread.sleep(10000);//sleep 输入值快的话，导致先执行notify，不会报错，但是并没有唤醒wait
                System.out.println("t1开始");
                synchronized (locker){
                    locker.wait();
                }
                System.out.println("t1结束");
            }catch (InterruptedException e){
                throw new RuntimeException();
            }
        });

        Thread t2 = new Thread(() -> {
            Scanner sc = new Scanner(System.in);
            System.out.println("输入任意值唤醒线程t1");
            sc.nextInt();//也是一种阻塞
            synchronized (locker) {
                locker.notify();
            }
        });


        t1.start();
        t2.start();
    }
}
